package com.chery.media.library.extend

import android.content.Context
import android.os.Parcelable
import com.tencent.mmkv.MMKV


/**
 * @author MoYe_PanDeng
 * @ClassName: MMKVExt
 * @Description: 存储扩展
 * @date: 2021/5/15
 */

fun initMMkv(context: Context) = MMKV.initialize(context)

fun mmkv() = MMKV.mmkvWithID("CHERY_MEDIA")

/**
 * 存储数据
 */
fun storageData(key: String, any: Any?) {
    when (any) {
        is String -> mmkv()?.encode(key, any)
        is Float -> mmkv()?.encode(key, any)
        is Boolean -> mmkv()?.encode(key, any)
        is Int -> mmkv()?.encode(key, any)
        is Long -> mmkv()?.encode(key, any)
        is Double -> mmkv()?.encode(key, any)
        is ByteArray -> mmkv()?.encode(key, any)
        is Set<*> -> mmkv()?.encode(key, any as Set<String>)
        is Parcelable -> mmkv()?.encode(key, any)
        else -> throw TypeNotPresentException("类型呢不存在 $key", ClassNotFoundException())
    }
}

/**
 * 获取数据
 */

fun getStorageInt(key: String): Int? = mmkv()?.decodeInt(key, 0)

fun getStorageDouble(key: String?): Double? = mmkv()?.decodeDouble(key, 0.0)

fun getStorageLong(key: String?): Long? = mmkv()?.decodeLong(key, 0)

fun getStorageBoolean(key: String?): Boolean? = mmkv()?.decodeBool(key, false)

fun getStorageFloat(key: String?): Float? = mmkv()?.decodeFloat(key, 0f)

fun getStorageByteArray(key: String?): ByteArray? = mmkv()?.decodeBytes(key)

fun getStorageString(key: String?): String? = mmkv()?.decodeString(key)

fun <T : Parcelable?> getStorageParcelable(key: String, t: Class<T>?): T? = mmkv()?.decodeParcelable(key, t)

fun <T : Set<String>> getStorageSet(key: String): T? = mmkv()?.decodeStringSet(key) as T?

/**
 * 清除对应key数据
 */
fun clearKeyData(key: String){
    mmkv()?.removeValueForKey(key)
}

/**
 * 清除所有数据
 */
fun clearAllData(){
    mmkv()?.clearAll()
}